﻿@using OBUCare.Core.Models
@using OBUCare.Web.Models
@using OBUCare.Web.Infrastructure
@using OBUCare.Core.Common
@{
    string url = Request.Url.ToString();
    var menuName = PageData["moduleID"] == null ? UIUtility.getMenuName(Request.Url.LocalPath) : PageData["moduleID"];

    ViewData["menuName"] = menuName;

}
<link rel="stylesheet" type="text/css" href="../../Content/tableCss.css" />
<table width="100%">
    <tr>
        <td style="text-align: center">
            <span style="font-weight: bold; font-size: 16px">流水单管理 </span>
        </td>
    </tr>
    <tr>
        <td style="text-align: left">
            @Html.Partial("SearchBy")
        </td>
    </tr>
    <tr>
        <td>&nbsp;
        </td>
    </tr>
    <tr>
        <td style="text-align: left">
            @using (Html.BeginForm("InsertConfirmed", "Transaction", FormMethod.Post, new { name = "formName", id = "formSerial" }))
            {  
                @Html.Partial("_FundInfo")
                @Html.Hidden("serialNos")
                <div style="text-align: right">
                    <label id="gridOutMoney">
                    </label>
                    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                    <label id="gridInMoney">
                    </label>
                    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                    <label id="gridTotal">
                    </label>
                </div>
                <div>
                    @(Html.Telerik().Grid<TransactionLogViewModel>()
        .Name("Grid")
        .DataKeys(keys => keys.Add(c => c.ID))
        .DataBinding(dataBinding => dataBinding.Ajax().
            Select("List", "Transaction", new { id = ViewBag.ID }))
        .Columns(columns =>
        {
            columns.Bound(o => o.ID)
               .ClientTemplate("<input name='checkedRecords' id='<#= ID #>' onclick='javascript:checkUser(this)'  type='checkbox' value='<#= ID #>' title='选中当前行'/> <#= ++index #>")
               .HeaderTemplate
               (
                   @<text>
                    <input type="checkbox" title="全选" id="checkAllRecords" />
                    </text>
               ).Width("8%");
            columns.Bound(o => o.SERIAL_NO).Width("15%");
            columns.Bound(o => o.USER_NO).Width("10%");
            columns.Bound(o => o.User_name).Width("18%");
            columns.Bound(o => o.TransactionType).Width("10%");
            columns.Bound(o => o.RepairPrice).Width("10%");
            columns.Bound(o => o.CREATED_DATE).Width("10%");
            columns.Bound(o => o.REMARK).Width("35%");
            columns.Bound(o => o.SERIAL_ID).Hidden();
            columns.Bound(o => o.ID).Hidden();
            columns.Bound(o => o.OPERATION_KIND);
        }).TableHtmlAttributes(new { style = "width:170%" })
        .Footer(false)
        .Scrollable(scroll => scroll.Height(CommonStyleForUI.Grid_Height))
        .ClientEvents(events => events.OnDataBinding("onDataBinding"))
                                                                  )
                </div>
    
      
                <p>
                    <input id="btnSubmit" type="button" value="生成" />
                    <input id="btnPrint" type="button" value="打印" />
                    <input type="button" value="录入发票" id="invoiceAdd" />
                </p>
            }
        </td>
    </tr>
</table>
@using (Html.BeginForm("Print", "Transaction", FormMethod.Post, new { @id = "ExportForm", target = "_blank" }))
{
    @Html.Hidden("SERIAL_ID", (ViewBag.SERIAL_ID as long?).ToText(), new { @id = "SERIAL_ID" })
    @Html.Hidden("Log_ID", ViewBag.Log_ID as string, new { @id = "Log_ID" })
}
<script type="text/javascript">

    $().ready(function () {

        //如果是提交完成后，则打开打印页面
        printAfterSubmit();

        //为全选框注册事件
        $('#checkAllRecords').click(function () {
            $("#Grid tbody input:checkbox").attr("checked", this.checked);
        });
        $("#btnSubmit").click(function () {
            return checkAmount();

        })
        $("#invoiceAdd").click(function () {
            onClick();
        })

        //点击打印
        $("#btnPrint").click(function () {

            //debugger;
            //判断是否选中日志
            strIDs = getCheckedOderIDs();
            if (strIDs.length <= 0) {
                alert("请选择待打印的流水信息");
                return false;
            }

            var list = $("#Grid tbody input:checkbox[name =checkedRecords][checked]");

            //判断选中的流水单是否已生成
            //判断选中的流水单号是否相同
            var serialID = "";
            var logsID = "";
            for (var i = 0; i < list.length; i++) {

                //获取选中的第一行的流水单值
                var tdsFirst = $(list[0]).parent().parent().find("td");
                if ($(tdsFirst[8]).html() != null && $(tdsFirst[8]).html().toString().length > 0) {
                    serialID = $(tdsFirst[8]).html().toString();
                }
                else {
                    alert("请选中已有流水单号的信息");
                    return false;
                }

                //正常获取选中的流水单值
                var tds = $(list[i]).parent().parent().find("td");

                if ($(tds[8]).html() == null && $(tds[8]).html().toString() == "") {
                    alert("请选中已有流水单号的信息");
                    return false;
                }
                var checkserial = $(tds[8]).html() == null ? "" : $(tds[8]).html().toString();

                logsID += $(tds[9]).html().toString() + ",";

                if (checkserial != serialID) {
                    alert("请选择流水单一致的信息。");
                    return false;
                }
            }

            $("#SERIAL_ID").val(serialID);
            $("#Log_ID").val(logsID);

            var form = $("#ExportForm");
            form.submit();
        });

    });

    //提交后，直接打开打印页面
    function printAfterSubmit()
    {
        var serialID=$("#SERIAL_ID").val();
        var logsID=$("#Log_ID").val(); 

        if((!serialID.StringIsNullOrEmpty())&&(!(logsID.StringIsNullOrEmpty())))
        {
            var form = $("#ExportForm");
            form.submit();
            $("#SERIAL_ID").val("");
            $("#Log_ID").val(""); 
        }
    }

    //复选框触发 选中事件 如果流水单号不为空 则选中所有流水单号相同的 如果流水单号为空 则选中所有客编相同的
    function checkUser(model) {
        //debugger;
        var sumAmount = 0;
        var list = $("#Grid tbody input:checkbox[name =checkedRecords][checked]");
        var inMoney=0;
        var outMoney=0;
        for (var i = 0; i < list.length; i++) {
            var tds = $(list[i]).parent().parent().find("td");
            var operationKind =parseInt($(tds[10]).html());
            var amount = $(tds[5]).html() == null ? "0" : $(tds[5]).html().toString();            
            switch (operationKind) { 
                case  @TransactionType.RepairObu.ToInt(): //标签维修
                case  @TransactionType.IssueSpareTape.ToInt()://背胶销售
                case  @TransactionType.IssueBase.ToInt()://底座销售
                case  @TransactionType.CollectsDeposit.ToInt()://收取押金
                case  @TransactionType.RepairServiceFee.ToInt()://服务费
                    inMoney+=parseInt(amount);
                    break;
                case  @TransactionType.ReturnDeposit.ToInt()://退还押金
                    outMoney+=parseInt(amount);
                    break;
                case  @TransactionType.OneRepair.ToInt()://一口价
                    inMoney+=parseInt(amount);
                    break;
            }

            sumAmount += parseInt(amount);
        }
        document.getElementById("gridOutMoney").innerHTML = "退款共计：" + outMoney*(-1) + "(元)"; //退款共计连接正数
        document.getElementById("gridInMoney").innerHTML = "收款共计：" + inMoney + "(元)";
        var total=outMoney+inMoney;
        if(total>0)
        {
            document.getElementById("gridTotal").innerHTML = "共计收款：" + total + "(元)";
        }
        else
        {
            document.getElementById("gridTotal").innerHTML = "共计退款：" + total*(-1) + "(元)";
        }
        if(inMoney>0)
        {
            $("#AMOUNT0").val(inMoney);
        }
        else
        {
            $("#AMOUNT0").val("");
        }
    }

    //获取被选中的ID
    function getCheckedOderIDs() {
        //获取被选中的ID
        var strBuff = new StringBuffer();
        $("#Grid tbody input:checkbox[name =checkedRecords][checked]").each(function () {
            strBuff.append(this.value);
        });
        strIDs = strBuff.arrayToString(",");
        return strIDs;
    }

    function checkAmount() {
        //debugger;
        //判断是否选中日志
        strIDs = getCheckedOderIDs();
        if (strIDs.length <= 0) {
            alert("请选择操作日志信息");
            return;
        }
        //判断金额
        var amount = 0;
        $.get("/Transaction/GetFundTypes","",function(result){
            if (result!="false") {
                var data = $.parseJSON(result);
                if (data.Types.length>0) {
                    for (var i = 0; i < data.Types.length; i++) {
                        var v = $("#AMOUNT" + data.Types[i]).val()
                        if (v != "") {
                            if (v < 0) {
                                alert("金额必须大于0"); return false;
                            }else if(/^(\+|-)?\d+$/.test( v ) ==false)
                            {
                                alert("金额输入不正确");return false;
                            }
                            else {
                                amount += parseInt(v);
                            }
                        }
                    }
                    var list = $("#Grid tbody input:checkbox[name =checkedRecords][checked]");
                    var tdsFirst = $(list[0]).parent().parent().find("td");
                    var returnDeposit = ""+@(TransactionType.ReturnDeposit.ToInt())+"";
                    //如果只是针对独一的退还押金 则直接通过
                    if(list.length==1 && $(tdsFirst[10]).html()==returnDeposit) {
                        $('#formSerial').submit();
                        return;
                    }
                  
                    var count = 0;

                    var serialID = "";
                    for (var i = 0; i < list.length; i++) {
                        //比较选中的流水单号是否一致
                        var tdsFirst = $(list[0]).parent().parent().find("td");

                        var tds = $(list[i]).parent().parent().find("td");
                        if ($(tdsFirst[8]).html() != null && $(tdsFirst[8]).html().toString().length > 0) {
                            serialID = $(tdsFirst[8]).html().toString();
                        }
                        var checkserial = $(tds[8]).html() == null ? "" : $(tds[8]).html().toString();
                        if (checkserial != serialID) {
                            alert("请选择流水单一致的信息。");
                            return;
                        }
                        var operationKind =parseInt($(tds[10]).html());
                        var operationAmount = $(tds[5]).html() == null ? "0" : $(tds[5]).html().toString();            
                        switch (operationKind) { 
                            case  @TransactionType.RepairObu.ToInt(): //标签维修
                            case  @TransactionType.IssueSpareTape.ToInt()://背胶销售
                            case  @TransactionType.IssueBase.ToInt()://底座销售
                            case  @TransactionType.CollectsDeposit.ToInt()://收取押金
                            case  @TransactionType.RepairServiceFee.ToInt()://服务费
                            case  @TransactionType.OneRepair.ToInt()://一口价维修
                                count+=parseInt(operationAmount);
                                break;
                        }

                        //            count += parseInt($(tds[5]).html().toString());
                    }

                    //判断选中的客编是否一致，不一致不允许操作
                    var UserNo = "";
                    for (var i = 0; i < list.length; i++) {

                        //获取选中的第一行的客编
                        var tdsFirst = $(list[0]).parent().parent().find("td");
                        if ($(tdsFirst[2]).html() != null && $(tdsFirst[2]).html().toString().length > 0) {
                            UserNo = $(tdsFirst[2]).html().toString();
                        }
                        //正常获取选中的流水单值
                        var tds = $(list[i]).parent().parent().find("td");

                        var checkUserNo = $(tds[2]).html() == null ? "" : $(tds[2]).html().toString();

                        if (checkUserNo != UserNo) {
                            alert("请选择客编一致的信息。");
                            return;
                        }
                    }
                    
                    if (serialID&&serialID!="") {
                        $('#serialNos').val(serialID)
                        $.get("/Transaction/GetAllAmount",{serialID:serialID},function(data){
                            if (data!="false") {
                                var allAmount = parseFloat(data);
                                if (!allAmount||allAmount!=amount) {
                                    alert('涉及业务超出一笔，不允许单独修改');
                                }else{ 
                                    $('#formSerial').submit();
                                }
                            }else {
                                alert("获取选中流水单号来源总金额出错，请联系管理员！");
                            }
                        });
                    }else{
                        if (amount != count) {
                            alert("请输入与流水一致的金额！");
                            return;
                        }else{
                            $('#formSerial').submit();
                        }
                    }
                }
            }else {
                alert("获取金额时出错，请联系管理员！");
                return;
            }
        });  
    }

    function onClick() {

        //debugger;
        //判断是否选中日志
        strIDs = getCheckedOderIDs();
        if (strIDs.length <= 0) {
            alert("请选择操作日志信息");
            return false;
        }
        var list = $("#Grid tbody input:checkbox[name =checkedRecords][checked]");
        //判断选中的流水单是否已生成
        var serialID = "";
        for (var i = 0; i < list.length; i++) {
            //获取流水单值
            var tds = $(list[i]).parent().parent().find("td");
            if ($(tds[8]).html() != null && $(tds[8]).html().toString().length > 0)
                serialID += $(tds[8]).html().toString() + ",";
            else {
                alert("请选中已有流水单号的信息");
                return false;
            }
        }

        serialID = serialID.substring(0, serialID.length - 1);
        var jdata = { serialID: serialID };
        $.post("/Transaction/checkIsExistInvoice", jdata,
                        function (data) {
                            if (data.Success == false) {
                                alert(data.ErrorMsg);
                                return false;
                            }
                            else {
                                window.location = '/Invoice/Index?IDs=' + serialID;
                            }
                        });

    }



    var index = 0;

    function onDataBinding(e) {
        var grid = $('#Grid').data('tGrid')
        index = (grid.currentPage - 1) * grid.pageSize;
        e.data = {
            // the key ("category") specifies the variable name of the action method which will contain the specified value
            searchSql: $('#searchSql').val(),
            AgentNo: $('#AgentNo').val()
        };
    }

    function submitClick(){
        $.post
        $('#InsertConfirmed').submit();
    };
</script>
